package com.shop.cloud.common.security.component;

import cn.hutool.core.util.StrUtil;
import com.shop.cloud.common.core.constant.SecurityConstants;
import com.shop.cloud.common.security.annotation.Inside;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.AccessDeniedException;


/**
 * @author 辰
 * @date 2023年10月26日17:07:50
 * <p>
 * 服务间接口不鉴权处理逻辑
 */
@Slf4j
@Aspect
@AllArgsConstructor
public class BaseSecurityInsideAspect  implements Ordered {
	private final HttpServletRequest request;


	@SneakyThrows
	@Before("@within(inside) || @annotation(inside)")
	public void around(JoinPoint point, Inside inside) {
		// 实际注入的inside实体由表达式后一个注解决定，即是方法上的@Inside注解实体，若方法上无@Inside注解，则获取类上的
		if (inside == null) {
			Class<?> clazz = point.getTarget().getClass();
			inside = AnnotationUtils.findAnnotation(clazz, Inside.class);
		}
		String header = request.getHeader(SecurityConstants.FROM);
		if (inside.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
			log.warn("访问接口 {} 没有权限", point.getSignature().getName());
			throw new AccessDeniedException("访问被拒绝，没有权限");
		}
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 1;
	}
}
